<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <el-select
        v-model="value"
        filterable
        :filter-method="filterHandler"
        multiple
        @change="changeSelect"
        placeholder="请选择"
    >
      <div class="custom-checkbox" v-if="allDisplay">
        <span>
          <span>全选</span>
          <el-checkbox style="float: right" v-model="checked" @change="changeCheckBox"></el-checkbox>
        </span>
      </div>
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>

<script>

export default {
  name: 'App',
  data() {
    return {
      options: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],
      options1: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],
      value: [],
      checked: false,
      allDisplay: true
    }
  },
  methods: {
    changeCheckBox(val) {
      if(val === true){
        //全选功能
        console.log('---------------', this.options.map(item => item.value))
        this.value = this.options.map(item => item.value)
      } else {
        this.value = []
      }
    },
    filterHandler(queryString) {
      this.options = this.options1.filter(item => item.label.includes(queryString));
      this.allDisplay = this.options.length > 0
    },
    changeSelect(val) {
      let end = val[val.length - 1];
      if (!val.includes("选项0") && val.length === this.options.length) {
        val.unshift("选项0");
      } else if (val.includes("选项0") && val.length === 1) {
        this.options.map(item => {
          val.push(item.value);
        });
      } else if (
          val.includes("选项0") &&
          val.length - 1 < this.options.length &&
          end === "选项0"
      ) {
        val = [];
        this.options.map(item => {
          val.push(item.value);
        });
        val.unshift("选项0");
      } else if (val.includes("选项0") && val.length - 1 < this.options.length) {
        val = val.filter(item => {
          return item !== "选项0";
        });
      }
      this.value = val;
    }

  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.custom-checkbox {
  padding: 0 20px;
  height: 34px;
  line-height: 34px;
}
.custom-checkbox span {
  flex-direction: column;
  justify-content: space-between;
}
</style>
